#include <bits/stdc++.h>
#include <cstddef>
using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int len = 0;
        ListNode* p = head;
        while(p != NULL){
            ++len;
            p = p->next;
        }
        int t = len - n - 1;
        if(t < 0){
            ListNode* deleteNode = head;
            head = head->next;
            delete deleteNode;
        }
        else {
            p = head;
            for(int i=0; i<t; ++i){
                p = p->next;
            }
            ListNode *deleteNode = p->next;
            p->next = deleteNode->next;
            delete deleteNode;
        }
        return head;
    }
};

int main(){

}